﻿Imports ISNet.WebUI.WebGrid
Imports System.Data
Imports log4net

Partial Class _CheckPlan
    Inherits System.Web.UI.Page

    Public AlertText As String
    Public ScriptText As String
    Dim nowVersion As Integer
    Private Shared logger As ILog = LogManager.GetLogger("CheckPlan")

    Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
        Session.LCID = 2057
        If Session("users") Is Nothing Then
            Response.Redirect("LoginForm.aspx")
        End If
        
        If IsPostBack = False Then
            'Session("users") = "bb9233"
            'Session.Add("PlanYear", 2557)
            PlanYearsTxt.Text = Session("PlanYear")

            'Dim myVersion As Integer = getMyVersion(Session("users"))

            ' Session("prefilter")=

            GetData()
        End If
    End Sub

    Sub GetData()
        Dim username As String = Session("users")
        'Alert(username)
        Dim top_fct As String
        Dim version As Integer
        GetTopFct(username, Val(PlanYearsTxt.Text), 1, top_fct, version)

        If top_fct = "" Then
            Exit Sub
        End If

        Dim FCTDataSet As New DataSet

        Dim adap As New FundCenter2TableAdapters.BudgetDetailsTableAdapter

        Try
            Dim strVersion As String = ""
            strVersion = adap.getMaxVersion(top_fct, Val(PlanYearsTxt.Text))
            If strVersion.Length > 1 Then
                strVersion = "0"
            End If
            nowVersion = Val(strVersion)

            If nowVersion < version Then
                version = 1

            End If

        Catch ex As Exception
            version = 1
        End Try
        If version = 0 Then
            version = 1
        End If
        If nowVersion > version Then
            SendBtn.Visible = False
        End If

        GetChildWithVersion2(top_fct, Val(PlanYearsTxt.Text), 1, FCTDataSet, version)
        HdMyVersion.Value = version

        WebGrid1.ClearCachedDataSource()
        WebGrid1.DataSource = FCTDataSet.Tables("Items")
        WebGrid1.RebindDataSource()
        WebGrid2.Visible = True
        WebGrid3.Visible = True
        TabPanel2.Visible = True
        WebGrid2.DataSource = checkError04()
        Try
            WebGrid2.RebindDataSource()
        Catch ex As Exception
            logger.Error(ex.Message)
            logger.Error(ex.StackTrace)
        End Try

        WebGrid3.DataSource = checkError_No04()
        Try
            WebGrid3.RebindDataSource()
        Catch ex As Exception
            logger.Error(ex.Message)
            logger.Error(ex.StackTrace)
        End Try

    End Sub

    Sub GetTopFct(username As String, PlanYear As Decimal, FctGroup As String, ByRef fctCode As String, ByRef version As Integer)
        Dim adapter As New FundCenter2TableAdapters.FundCenterHierarchiesTableAdapter
        Dim datatable As New FundCenter2.FundCenterHierarchiesDataTable
        'Alert(username & PlanYear & FctGroup)
        datatable = adapter.GetTopFctByUser(username, PlanYear, FctGroup)
        Dim adap2 As New checkPlanDSTableAdapters.BudgetDetails1TableAdapter
        Try
            For Each row As FundCenter2.FundCenterHierarchiesRow In datatable
                fctCode = row.FundCenter_FundCenterCode

                Dim level As Integer = row.Level
                If level = 1 Then
                    version = 5
                ElseIf level = 2 Then
                    version = 4
                ElseIf level = 3 Then
                    version = 3
                ElseIf level = 4 Then
                    version = 2
                Else
                    version = 1

                End If

            Next

        Catch ex As Exception
            fctCode = ""
            version = 1
        End Try


    End Sub


    'Sub GetChildWithVersion(FundCenterCode As String, PlanYear As Decimal, FctGroup As String, ByRef ds As DataSet, ByRef CopyToVersion As Integer)


    '    Dim dt As DataTable = ds.Tables.Add("Items")
    '    dt.Columns.Add("FundCenterCode", Type.GetType("System.String"))
    '    dt.Columns.Add("FundCenterName", Type.GetType("System.String"))
    '    dt.Columns.Add("now_version", Type.GetType("System.Int32"))
    '    dt.Columns.Add("level", Type.GetType("System.Int32"))

    '    dt.Columns.Add("CreateDate", Type.GetType("System.String"))
    '    dt.Columns.Add("ReleaseFlag", Type.GetType("System.String"))
    '    Dim Radapter As New FundCenterRelationTableAdapters.FundCenterReleasesTableAdapter
    '    Dim Rdatatable As New FundCenterRelation.FundCenterReleasesDataTable
    '    Dim Fadapter As New FundCenterRelationTableAdapters.FundCenterHierarchiesTableAdapter
    '    Dim Fdatatable As New FundCenterRelationTableAdapters.FundCenterHierarchiesTableAdapter
    '    Dim Hadapter As New FundCenterRelationTableAdapters.FctHTableAdapter
    '    Dim Hdatatable As New FundCenterRelation.FctHDataTable
    '    Dim Cdatatable As New FundCenterRelation.FctHDataTable
    '    Dim Badapter As New FundCenterRelationTableAdapters.BudgetDetailsTableAdapter

    '    Hdatatable = Hadapter.GetDataByFctCode(FundCenterCode, PlanYear, FctGroup)
    '    Dim RootGroupPath As String = ""

    '    If Hdatatable.Count = 0 Then
    '        Exit Sub
    '    End If
    '    Dim r As DataRow
    '    'add root
    '    For Each Hrow As FundCenterRelation.FctHRow In Hdatatable
    '        RootGroupPath = Hrow.grouppath
    '        r = dt.NewRow()
    '        r("FundCenterCode") = Hrow.FundCenter_FundCenterCode
    '        r("FundCenterName") = Hrow.Description
    '        r("level") = Val(Left(Fadapter.GetOrgLevel(Hrow.FundCenter_FundCenterCode, PlanYear, FctGroup), 1))
    '        CopyToVersion = r("level")
    '        r("now_version") = 1
    '        Rdatatable = Radapter.GetDataByFCT(r("FundCenterCode"), PlanYear, r("now_version"))

    '        r("CreateDate") = ""
    '        r("ReleaseFlag") = ""
    '        For Each rrow As FundCenterRelation.FundCenterReleasesRow In Rdatatable
    '            r("CreateDate") = rrow.UpdatedDate
    '            r("ReleaseFlag") = rrow.ReleaseFlag
    '        Next
    '        If r("ReleaseFlag") = "" Then
    '            If Badapter.CountRecord(r("FundCenterCode"), PlanYear, r("now_version")) > 0 Then
    '                r("ReleaseFlag") = "N"
    '            End If
    '        End If
    '        dt.Rows.Add(r)
    '    Next
    '    'get child 1 level
    '    Hdatatable = Hadapter.GetDataByGroupPath(RootGroupPath & "__", PlanYear, FctGroup)
    '    Dim version As Integer
    '    For Each row As FundCenterRelation.FctHRow In Hdatatable
    '        r = dt.NewRow()
    '        r("FundCenterCode") = row.FundCenter_FundCenterCode
    '        r("FundCenterName") = row.Description
    '        r("level") = Val(Left(fadapter.GetOrgLevel(row.FundCenter_FundCenterCode, PlanYear, FctGroup), 1))
    '        'get child all
    '        Cdatatable = Hadapter.GetDataByGroupPath(row.grouppath & "%", PlanYear, FctGroup)
    '        If Cdatatable.Count = 0 Then
    '            r("now_version") = 1
    '        Else
    '            r("now_version") = r("level")
    '        End If
    '        version = r("now_version")
    '        Rdatatable = Radapter.GetDataByFCT(r("FundCenterCode"), PlanYear, r("now_version"))

    '        r("CreateDate") = ""
    '        r("ReleaseFlag") = ""
    '        For Each rrow As FundCenterRelation.FundCenterReleasesRow In Rdatatable
    '            r("CreateDate") = rrow.UpdatedDate
    '            r("ReleaseFlag") = rrow.ReleaseFlag
    '        Next
    '        If r("ReleaseFlag") = "" Then
    '            If Badapter.CountRecord(r("FundCenterCode"), PlanYear, r("now_version")) > 0 Then
    '                r("ReleaseFlag") = "N"
    '            End If
    '        End If

    '        dt.Rows.Add(r)
    '        'insert child
    '        For Each crow As FundCenterRelation.FctHRow In Cdatatable
    '            r = dt.NewRow()
    '            r("FundCenterCode") = crow.FundCenter_FundCenterCode
    '            r("FundCenterName") = crow.Description

    '            r("level") = Val(Left(Fadapter.GetOrgLevel(crow.FundCenter_FundCenterCode, PlanYear, FctGroup), 1))

    '            r("now_version") = version

    '            Rdatatable = Radapter.GetDataByFCT(r("FundCenterCode"), PlanYear, r("now_version"))

    '            r("CreateDate") = ""
    '            r("ReleaseFlag") = ""
    '            For Each rrow As FundCenterRelation.FundCenterReleasesRow In Rdatatable
    '                r("CreateDate") = rrow.UpdatedDate
    '                r("ReleaseFlag") = rrow.ReleaseFlag
    '            Next
    '            If r("ReleaseFlag") = "" Then
    '                If Badapter.CountRecord(r("FundCenterCode"), PlanYear, r("now_version")) > 0 Then
    '                    r("ReleaseFlag") = "N"
    '                End If
    '            End If
    '            dt.Rows.Add(r)
    '        Next



    '    Next

    'End Sub

    Sub GetChildWithVersion2(FundCenterCode As String, PlanYear As Decimal, FctGroup As String, ByRef ds As DataSet, ByRef CopyToVersion As Integer)


        Dim dt As DataTable = ds.Tables.Add("Items")
        dt.Columns.Add("FundCenterCode", Type.GetType("System.String"))
        dt.Columns.Add("FundCenterName", Type.GetType("System.String"))
        dt.Columns.Add("now_version", Type.GetType("System.Int32"))
        dt.Columns.Add("level", Type.GetType("System.Int32"))

        dt.Columns.Add("CreateDate", Type.GetType("System.String"))
        dt.Columns.Add("ReleaseFlag", Type.GetType("System.String"))
        Dim Radapter As New FundCenterRelationTableAdapters.FundCenterReleasesTableAdapter
        Dim Rdatatable As New FundCenterRelation.FundCenterReleasesDataTable
        Dim Fadapter As New FundCenterRelationTableAdapters.FundCenterHierarchiesTableAdapter
        Dim Fdatatable As New FundCenterRelationTableAdapters.FundCenterHierarchiesTableAdapter
        Dim Hadapter As New FundCenterRelationTableAdapters.FctHTableAdapter
        Dim Hdatatable As New FundCenterRelation.FctHDataTable
        Dim Cdatatable As New FundCenterRelation.FctHDataTable
        Dim Badapter As New FundCenterRelationTableAdapters.BudgetDetailsTableAdapter

        Hdatatable = Hadapter.GetDataByFctCode(FundCenterCode, PlanYear, FctGroup)
        Dim RootGroupPath As String = ""

        If Hdatatable.Count = 0 Then
            Exit Sub
        End If
        Dim r As DataRow
        'add root
        Dim rversion As Integer = 0
        Dim adap2 As New checkPlanDSTableAdapters.FundCenterReleasesTableAdapter
        For Each Hrow As FundCenterRelation.FctHRow In Hdatatable
            RootGroupPath = Hrow.grouppath
            r = dt.NewRow()
            r("FundCenterCode") = Hrow.FundCenter_FundCenterCode
            r("FundCenterName") = Hrow.Description
            r("level") = Val(Left(Fadapter.GetOrgLevel(Hrow.FundCenter_FundCenterCode, PlanYear, FctGroup), 1))
            CopyToVersion = r("level")

            Dim maxvers As String = ""
            maxvers = adap2.GetMaxVersion(Hrow.FundCenter_FundCenterCode, PlanYear)
            If maxvers <= 1 Then
                r("now_version") = 1
            Else
                r("now_version") = r("level")
                rversion = Val(r("level"))
            End If
            Rdatatable = Radapter.GetDataByFCT(r("FundCenterCode"), PlanYear, r("now_version"))

            r("CreateDate") = ""
            r("ReleaseFlag") = ""
            For Each rrow As FundCenterRelation.FundCenterReleasesRow In Rdatatable
                r("CreateDate") = If(rrow.IsUpdatedDateNull, rrow.CreatedDate, rrow.UpdatedDate)
                r("ReleaseFlag") = rrow.ReleaseFlag
            Next
            If r("ReleaseFlag") = "" Then
                If Badapter.CountRecord(r("FundCenterCode"), PlanYear, r("now_version")) > 0 Then
                    r("ReleaseFlag") = "N"
                End If
            End If
            dt.Rows.Add(r)
        Next
        'get child 1 level
        If rversion > 1 Then

            Hdatatable = Hadapter.GetDataByGroupPath(RootGroupPath & "__", PlanYear, FctGroup)
            Dim version As Integer
            For Each row As FundCenterRelation.FctHRow In Hdatatable
                r = dt.NewRow()
                r("FundCenterCode") = row.FundCenter_FundCenterCode
                r("FundCenterName") = row.Description
                r("level") = Val(Left(Fadapter.GetOrgLevel(row.FundCenter_FundCenterCode, PlanYear, FctGroup), 1))
                'get child all
                Cdatatable = Hadapter.GetDataByGroupPath(row.grouppath & "%", PlanYear, FctGroup)
                If Cdatatable.Count = 0 Then
                    r("now_version") = 1
                Else
                    r("now_version") = r("level")
                End If
                If rversion <> 0 Then
                    r("now_version") = rversion
                End If
                version = r("now_version")
                Rdatatable = Radapter.GetDataByFCT(r("FundCenterCode"), PlanYear, r("now_version"))

                r("CreateDate") = ""
                r("ReleaseFlag") = ""
                For Each rrow As FundCenterRelation.FundCenterReleasesRow In Rdatatable
                    r("CreateDate") = If(rrow.IsUpdatedDateNull, rrow.CreatedDate, rrow.UpdatedDate)
                    r("ReleaseFlag") = rrow.ReleaseFlag
                Next
                If r("ReleaseFlag") = "" Then
                    If Badapter.CountRecord(r("FundCenterCode"), PlanYear, r("now_version")) > 0 Then
                        r("ReleaseFlag") = "N"
                    End If
                End If

                dt.Rows.Add(r)
                'insert child
                For Each crow As FundCenterRelation.FctHRow In Cdatatable
                    r = dt.NewRow()
                    r("FundCenterCode") = crow.FundCenter_FundCenterCode
                    r("FundCenterName") = crow.Description

                    r("level") = Val(Left(Fadapter.GetOrgLevel(crow.FundCenter_FundCenterCode, PlanYear, FctGroup), 1))

                    r("now_version") = version
                    If rversion <> 0 Then
                        r("now_version") = rversion
                    End If
                    Rdatatable = Radapter.GetDataByFCT(r("FundCenterCode"), PlanYear, r("now_version"))

                    r("CreateDate") = ""
                    r("ReleaseFlag") = ""
                    For Each rrow As FundCenterRelation.FundCenterReleasesRow In Rdatatable
                        r("CreateDate") = If(rrow.IsUpdatedDateNull, rrow.CreatedDate, rrow.UpdatedDate)
                        r("ReleaseFlag") = rrow.ReleaseFlag
                    Next
                    If r("ReleaseFlag") = "" Then
                        If Badapter.CountRecord(r("FundCenterCode"), PlanYear, r("now_version")) > 0 Then
                            r("ReleaseFlag") = "N"
                        End If
                    End If
                    dt.Rows.Add(r)
                Next



            Next

        End If

    End Sub

    'Sub GetChildWithVersion(FundCenterCode As String, PlanYear As Decimal, FctGroup As String, ByRef ds As DataSet, ByRef version As Integer)

    '    Dim dt As DataTable = ds.Tables.Add("Items")
    '    dt.Columns.Add("FundCenterCode", Type.GetType("System.String"))
    '    dt.Columns.Add("version", Type.GetType("System.String"))
    '    dt.Columns.Add("Level", Type.GetType("System.Int32"))
    '    dt.Columns.Add("FundCenterName", Type.GetType("System.String"))
    '    dt.Columns.Add("CreateDate", Type.GetType("System.String"))
    '    dt.Columns.Add("ReleaseFlag", Type.GetType("System.String"))
    '    dt.Columns.Add("Now_version", Type.GetType("System.Int32"))
    '    Dim adapter As New FundCenter2TableAdapters.FundCenterHierarchiesTableAdapter
    '    Dim datatable As New FundCenter2.FundCenterHierarchiesDataTable


    '    Dim r As DataRow
    '    r = dt.NewRow()
    '    r("FundCenterCode") = FundCenterCode
    '    r("Now_version") = version

    '    Dim level As Integer

    '    level = adapter.GetLevel(FundCenterCode, PlanYear, FctGroup) / 10
    '    If level = 0 Then
    '        level = adapter.GetLevelByChild(FundCenterCode, PlanYear, FctGroup) / 10
    '    End If

    '    r("Level") = level
    '    HdMyVersion.Value = level
    '    Dim fadapter As New FundCenter2TableAdapters.FundCentersTableAdapter
    '    r("FundCenterName") = fadapter.GetName(FundCenterCode, PlanYear)
    '    Dim adap2 As New FundCenter2TableAdapters.fundCenterDetailTableAdapter
    '    For Each row As FundCenter2.fundCenterDetailRow In adap2.GetDataFundCenter(FundCenterCode, PlanYear, version)
    '        Try
    '            r("CreateDate") = row.UpdatedDate.ToLongDateString
    '        Catch ex As Exception
    '            r("CreateDate") = ""
    '        End Try

    '        r("ReleaseFlag") = row.ReleaseFlag

    '    Next


    '    dt.Rows.Add(r)

    '    datatable = adapter.GetDataByParentUser(Session("users"), PlanYear, FctGroup, FundCenterCode)

    '    For Each row As FundCenter2.FundCenterHierarchiesRow In datatable
    '        GetChild(FundCenterCode, row.FundCenter_FundCenterCode, ds, dt, PlanYear, FctGroup, version)
    '    Next




    'End Sub
    'Sub GetChild(top_code As String, ByVal parent_id As String, ByRef ds As DataSet, ByRef dt As DataTable, PlanYear As Decimal, FctGroup As String, version As Decimal)

    '    Dim adapter As New FundCenter2TableAdapters.FundCenterHierarchiesTableAdapter
    '    Dim datatable As New FundCenter2.FundCenterHierarchiesDataTable
    '    datatable = adapter.GetDataByParentUser(Session("users"), PlanYear, FctGroup, parent_id)
    '    Dim ChildAmount As Decimal
    '    Dim Relate As Decimal
    '    Dim r As DataRow

    '    r = dt.NewRow()
    '    r("FundCenterCode") = parent_id

    '    ChildAmount = adapter.CountChild(parent_id, PlanYear, FctGroup)
    '    Relate = adapter.CountRelate(top_code, parent_id, PlanYear, FctGroup)

    '    r("Now_version") = version

    '    Dim level As Integer

    '    level = adapter.GetLevel(parent_id, PlanYear, FctGroup) / 10
    '    If level = 0 Then
    '        level = adapter.GetLevelByChild(parent_id, PlanYear, FctGroup) / 10
    '    End If
    '    r("Level") = level

    '    Dim fadapter As New FundCenter2TableAdapters.FundCentersTableAdapter
    '    r("FundCenterName") = fadapter.GetName(parent_id, PlanYear)

    '    Dim adap2 As New FundCenter2TableAdapters.fundCenterDetailTableAdapter
    '    For Each row As FundCenter2.fundCenterDetailRow In adap2.GetDataFundCenter(parent_id, PlanYear, version)
    '        Try
    '            r("CreateDate") = row.UpdatedDate.ToLongDateString
    '        Catch ex As Exception
    '            r("CreateDate") = ""
    '        End Try


    '        r("ReleaseFlag") = row.ReleaseFlag

    '    Next

    '    dt.Rows.Add(r)

    '    For Each row As FundCenter2.FundCenterHierarchiesRow In datatable
    '        GetChild(top_code, row.FundCenter_FundCenterCode, ds, dt, PlanYear, FctGroup, version)
    '    Next
    'End Sub





    Protected Sub WebGrid1_InitializeDataSource(sender As Object, e As DataSourceEventArgs) Handles WebGrid1.InitializeDataSource
        GetData()

    End Sub


    Protected Sub WebGrid1_InitializeRow(sender As Object, e As RowEventArgs) Handles WebGrid1.InitializeRow
        'If Not e.Row.Cells.GetNamedItem("FundCenter") Is Nothing Then
        '    Dim lbl As New Label()
        '    lbl.Text = "testItem"

        '    ' Dim lt As New Literal("Maybe I also want to add a literal")
        '    'Dim ddl As New DropDownList()
        '    'ddl.Items.Add(New ListItem("I also want a dropdownlist"))

        '    e.Row.Cells.GetNamedItem("FundCenter").GetTemplateContainer().Controls.Add(lbl)
        '    ' e.Row.Cells.GetNamedItem("fundCenter").GetTemplateContainer().Controls.Add(ddl)



        'End If


        Dim imag As New Image
        imag = CType(e.Row.Cells.GetNamedItem("FundCenter").GetTemplateContainer().FindControl("Image1"), Image)
        Try
            If e.Row.GetDataRow("ReleaseFlag") = "Y" Then
                imag.ToolTip = "ส่งแผนแล้ว"
                imag.ImageUrl = "Images/planIc/sendIc.png"
            ElseIf e.Row.GetDataRow("ReleaseFlag") = "N" Then
                imag.ToolTip = "ยังไม่ได้ส่งแผน"
                imag.ImageUrl = "Images/planIc/nosend.png"
            Else
                imag.ImageUrl = "Images/planIc/nobuild.png"
                imag.ToolTip = "ยังไม่ได้สร้างแผน"
            End If
        Catch ex As Exception
            imag.ImageUrl = "Images/planIc/nobuild.png"
        End Try

        Dim lb As New Label
        lb = CType(e.Row.Cells.GetNamedItem("FundCenter").GetTemplateContainer().FindControl("Label2"), Label)

        Dim shif As String = ""
        Dim forn As Integer = Val(HdMyVersion.Value) - Val(e.Row.GetDataRow("level"))
        ' MsgBox(HdMyVersion.Value)
        For i As Integer = 1 To forn
            shif = shif & "--"
        Next
        lb.Text = shif
        ' MsgBox(Val(e.Row.GetDataRow("level")))
        ' e.Row.Cells.GetNamedItem("FundCenter").GetTemplateContainer().Controls.Add(lbl)



        ' Dim imagR As New Image
        ' imagR = CType(e.Row.Cells.GetNamedItem("Release").GetTemplateContainer().FindControl("ImageR"), Image)
        Try
            'Dim countr As Integer = 0
            'Dim adapr As New FundCenter2TableAdapters.FundCenterReleasesTableAdapter
            'countr = adapr.getRelease(e.Row.GetDataRow("FundCenterCode"), e.Row.GetDataRow("Now_version"), Val(Session("PlanYear")))

            Dim permission As Boolean
            If Val(Session("RoleType")) = 2 Then
                permission = False
            Else
                Select Case Val(Session("RoleType"))
                    Case 3
                        If Val(e.Row.GetDataRow("level")) <= 2 Then
                            permission = True
                        Else
                            permission = False
                        End If
                    Case 4
                        If Val(e.Row.GetDataRow("level")) <= 3 Then
                            permission = True
                        Else
                            permission = False
                        End If
                    Case 5

                        permission = True
                    Case 1
                        permission = True
                End Select

            End If

            'If countr > 0 Then
            '    If permission = True Then
            '        imagR.Visible = True
            '    Else
            '        imagR.Visible = False
            '    End If

            'Else
            '    imagR.Visible = False
            'End If
        Catch ex As Exception
            ' imagR.Visible = False
            logger.Error(ex.Message)
            logger.Error(ex.StackTrace)
        End Try
    End Sub

    Protected Sub WebGrid1_InitializePostBack(sender As Object, e As PostbackEventArgs) Handles WebGrid1.InitializePostBack

        If e.Action = PostBackAction.Custom Then
            Dim data As String = TryCast(Request("data"), String)

            'WebGrid1.ClientAction.Alert(data)
            Dim dd = data.Split(",")
            Dim fundCen As String = dd(0)
            Dim version As String = dd(1)
            Dim countr As Integer = 0
            Dim adapr As New FundCenter2TableAdapters.FundCenterReleasesTableAdapter
            countr = adapr.getRelease(fundCen, version, Val(Session("PlanYear")))

            If countr > 0 Then
                adapr.cencelRelease("N", Date.Now, Session("users"), fundCen, Val(Session("PlanYear")), Val(Session("PlanYear")), Val(version))

            Else
                WebGrid1.ClientAction.Alert("แผนนี้ถูก copy version แล้ว ไม่สามารถยกเลิกได้")
            End If


            WebGrid1.ClientAction.Refresh()
        End If
    End Sub

    Protected Sub WebGrid2_InitializeDataSource(sender As Object, e As DataSourceEventArgs) Handles WebGrid2.InitializeDataSource
        Exit Sub
        Dim fundCenter As String = ""
        Dim dd As New DataTable
        dd = WebGrid1.DataSource
        If dd.Rows.Count = 0 Then
            Exit Sub
        End If
        Dim x As Integer = 0
        For Each row As DataRow In dd.Rows
            If x = 0 Then
                fundCenter = fundCenter & row("FundCenterCode")
            Else
                fundCenter = fundCenter & "," & row("FundCenterCode")
            End If

            x = x + 1

        Next
        Try
            WebGrid2.DataSource = checkError04(fundCenter)
        Catch ex As Exception
            logger.Error(ex.Message)
            logger.Error(ex.StackTrace)
        End Try
        ' MsgBox(dd.Rows.Count)



    End Sub

    Protected Sub WebGrid3_InitializeDataSource(sender As Object, e As DataSourceEventArgs) Handles WebGrid3.InitializeDataSource
        Exit Sub
        Dim fundCenter As String = ""
        Dim dd As New DataTable
        dd = WebGrid1.DataSource
        If dd.Rows.Count = 0 Then
            Exit Sub
        End If
        Dim x As Integer = 0
        For Each row As DataRow In dd.Rows
            If x = 0 Then
                fundCenter = fundCenter & row("FundCenterCode")
            Else
                fundCenter = fundCenter & "," & row("FundCenterCode")
            End If

            x = x + 1

        Next
        Try
            WebGrid3.DataSource = checkError_No04(fundCenter)

        Catch ex As Exception
            logger.Error(ex.Message)
            logger.Error(ex.StackTrace)
        End Try

        ' MsgBox(dd.Rows.Count)
    End Sub


    Protected Sub CheckBtn_Click(sender As Object, e As ImageClickEventArgs) Handles CheckBtn.Click
        Dim dd As New DataTable
        dd = WebGrid1.DataSource
        Try
            If Val(dd.Rows.Count) = 0 Then
                Alert("ไม่มีแผนที่จะตรวจสอบได้")
                Exit Sub
            End If
        Catch ex As Exception
            Alert("ไม่มีแผนที่จะตรวจสอบได้")
            Exit Sub
        End Try
        TabPanel2.Visible = True
        TabContainer1.ActiveTabIndex = 2

        ' MsgBox(fundCenter)
        WebGrid2.DataSource = checkError04()
        ' WebGrid2.ClearCachedDataSource()
        ' WebGrid2.RebindDataSource()
        WebGrid3.DataSource = checkError_No04()
        ' WebGrid3.ClearCachedDataSource()
        'WebGrid3.RebindDataSource()
        SendBtn.Enabled = True

        logger.Info("User " & Session("users") & " verify budget plan")
        Dim dt As New DataTable
        Dim dt2 As New DataTable

        dt.Merge(dt2)

        Dim i As Integer = 0
        i = WebGrid2.RootTable.Rows.Count
        i = i + WebGrid3.RootTable.Rows.Count
        If i = 0 Then
            Alert("ไม่มีข้อผิดพลาด ทำการส่งแผนได้")
        Else
            Alert("มีข้อผิดพลาด กรุณาแก้ไขก่อนทำการส่งแผน")
	End If

    End Sub

    Function checkError04() As DataTable

        Dim totalFundCenter As String = ""
        Dim dd As New DataTable
        dd = WebGrid1.DataSource
        If dd.Rows.Count = 0 Then
            Exit Function
        End If

        Dim dt As New DataTable

        dt.Columns.Add("FundCenterCode", GetType(String))
        'dt.Columns.Add("FundCName", GetType(String))
        dt.Columns.Add("CmmtCode", GetType(String))
        dt.Columns.Add("Project_ProjectCode", GetType(String))
        dt.Columns.Add("ActivityTypeCode", GetType(String))
        dt.Columns.Add("NewQuantity", GetType(String))
        dt.Columns.Add("ReplaceQuantity", GetType(String))
        dt.Columns.Add("Amount", GetType(Decimal))
        dt.Columns.Add("err", GetType(String))

        Dim adap4 As New checkPlanDSTableAdapters.BudgetDetailsTableAdapter
        Dim check As New checkPlanDS.BudgetDetailsDataTable
        Dim text As String = "ISNULL(Amount,0) as Amount, ISNULL(NewQuantity,0) as NewQuantity, ISNULL(ReplaceQuantity,0) as ReplaceQuantity, ISNULL(CONVERT(VARCHAR(255),BudgetDetails.ActivityType_ActivityTypeCode), CONVERT(VARCHAR(255),(ISNULL(BudgetDetails.AssetNo,'') + ' ' + ISNULL(BudgetDetails.AssetDescription,'')))) AS ActivityType_ActivityTypeCode, FundCenter_FundCenterCode,   FundCenter_PlanYear, ISNULL(Project_ProjectCode, ' ') AS Project_ProjectCode, Project_PlanYear, Project_FundCenterCode, ISNULL(Cmmt_CmmtCode, ' ')    AS Cmmt_CmmtCode, Cmmt_PlanYear"
        Dim sql4 As String = ""



        For Each rows As DataRow In dd.Rows

            sql4 = " select " & text & ", '1' as err from  BudgetDetails where FormId='F04' and left(AssetNo,1) = '9' and Attachments_amount = 0 and FundCenter_FundCenterCode = '" & rows("FundCenterCode") & "' and BudgetDetails.Version = '" & rows("Now_version") & "' and BudgetDetails.PlanYear = " & Val(PlanYearsTxt.Text)
            sql4 += " union select " & text & " ,  '1' as err from  BudgetDetails , ActivityTypes "
            sql4 += " where  BudgetDetails.FormId='F04' and BudgetDetails.ActivityType_ActivityTypeCode =  ActivityTypes.ActivityTypeCode and BudgetDetails.ActivityType_PlanYear = ActivityTypes.PlanYear and  ActivityTypes.AttachmentFlag = 'Y' and  Attachments_amount = 0 and BudgetDetails.FundCenter_FundCenterCode  = '" & rows("FundCenterCode") & "' and BudgetDetails.Version = '" & rows("Now_version") & "'" & " and BudgetDetails.PlanYear = " & Val(PlanYearsTxt.Text)
            sql4 += " union select " & text & " ,'1' as err from  BudgetDetails , ActivityTypes "
            sql4 += " where BudgetDetails.FormId='F04' and BudgetDetails.ActivityType_ActivityTypeCode =  ActivityTypes.ActivityTypeCode and BudgetDetails.ActivityType_PlanYear = ActivityTypes.PlanYear and   (ActivityTypes.Price = 0 or ActivityTypes.Price is null) and  Attachments_amount = 0 and BudgetDetails.FundCenter_FundCenterCode  = '" & rows("FundCenterCode") & "' and BudgetDetails.Version = '" & rows("Now_version") & "'" & " and BudgetDetails.PlanYear = " & Val(PlanYearsTxt.Text)
            sql4 += " union select " & text & " ,'4' as err from  BudgetDetails , ActivityTypes "
            sql4 += " where BudgetDetails.FormId='F04' and budgetDetails.ActivityType_ActivityTypecode NOT IN(Select ActivityType_ActivityTypeCode from Budget12) and BudgetDetails.FundCenter_FundCenterCode  = '" & rows("FundCenterCode") & "' and BudgetDetails.Version = '" & rows("Now_version") & "'" & " and BudgetDetails.PlanYear = " & Val(PlanYearsTxt.Text)
            sql4 += " union select ISNULL(BudgetDetails.Amount,0) as Amount, ISNULL(BudgetDetails.NewQuantity,0) as NewQuantity, ISNULL(BudgetDetails.ReplaceQuantity,0) as ReplaceQuantity, ISNULL(CONVERT(VARCHAR(255),BudgetDetails.ActivityType_ActivityTypeCode), CONVERT(VARCHAR(255),(ISNULL(BudgetDetails.AssetNo,'') + ' ' + ISNULL(BudgetDetails.AssetDescription,'')))) AS ActivityType_ActivityTypeCode, BudgetDetails.FundCenter_FundCenterCode, BudgetDetails.FundCenter_PlanYear, ISNULL(BudgetDetails.Project_ProjectCode, ' ') AS Project_ProjectCode, BudgetDetails.Project_PlanYear, BudgetDetails.Project_FundCenterCode, ISNULL(BudgetDetails.Cmmt_CmmtCode, ' ') AS Cmmt_CmmtCode, BudgetDetails.Cmmt_PlanYear ,'4' as err from BudgetDetails INNER JOIN Budget12 ON BudgetDetails.Id = Budget12.BudgetDetail_Id "
            sql4 += " where BudgetDetails.FormId='F04' AND BudgetDetails.Amount <> 0 and (Amount1 + Amount2 + Amount3 + Amount4 + Amount5 + Amount6 + Amount7 + Amount8 + Amount9 + Amount10 + Amount11 + Amount12) = 0 and BudgetDetails.FundCenter_FundCenterCode  = '" & rows("FundCenterCode") & "' and BudgetDetails.Version = '" & rows("Now_version") & "' " & " and BudgetDetails.PlanYear = " & Val(PlanYearsTxt.Text)
            sql4 += " and Budget12.FundCenter_FundCenterCode  = '" & rows("FundCenterCode") & "' and Budget12.Version = '" & rows("Now_version") & "'  and Budget12.PlanYear = " & Val(PlanYearsTxt.Text)
            sql4 += " union select ISNULL(BudgetDetails.Amount,0) as Amount, ISNULL(BudgetDetails.NewQuantity,0) as NewQuantity, ISNULL(BudgetDetails.ReplaceQuantity,0) as ReplaceQuantity, ISNULL(CONVERT(VARCHAR(255),BudgetDetails.ActivityType_ActivityTypeCode), CONVERT(VARCHAR(255),(ISNULL(BudgetDetails.AssetNo,'') + ' ' + ISNULL(BudgetDetails.AssetDescription,'')))) AS ActivityType_ActivityTypeCode, BudgetDetails.FundCenter_FundCenterCode, BudgetDetails.FundCenter_PlanYear, ISNULL(BudgetDetails.Project_ProjectCode, ' ') AS Project_ProjectCode, BudgetDetails.Project_PlanYear, BudgetDetails.Project_FundCenterCode, ISNULL(BudgetDetails.Cmmt_CmmtCode, ' ') AS Cmmt_CmmtCode, BudgetDetails.Cmmt_PlanYear ,'5' as err from BudgetDetails INNER JOIN Budget12 ON BudgetDetails.Id = Budget12.BudgetDetail_Id "
            sql4 += " where BudgetDetails.FormId='F04' AND BudgetDetails.Amount <> 0 and (BudgetDetails.Amount <> (Amount1 + Amount2 + Amount3 + Amount4 + Amount5 + Amount6 + Amount7 + Amount8 + Amount9 + Amount10 + Amount11 + Amount12)) and BudgetDetails.FundCenter_FundCenterCode  = '" & rows("FundCenterCode") & "' and BudgetDetails.Version = '" & rows("Now_version") & "' " & " and BudgetDetails.PlanYear = " & Val(PlanYearsTxt.Text)
            sql4 += " and Budget12.FundCenter_FundCenterCode  = '" & rows("FundCenterCode") & "' and Budget12.Version = '" & rows("Now_version") & "'  and Budget12.PlanYear = " & Val(PlanYearsTxt.Text)
            sql4 += " and (Amount1 + Amount2 + Amount3 + Amount4 + Amount5 + Amount6 + Amount7 + Amount8 + Amount9 + Amount10 + Amount11 + Amount12) <> 0 "

            adap4.GetDataByFilter(check, sql4)



            If check.Count > 0 Then

                Dim txtErr As String = ""
                Dim haveatt As Boolean
                For Each row As checkPlanDS.BudgetDetailsRow In check
                    If row.err = 1 Then

                        txtErr = "ครุภัณฑ์นี้ต้องการเอกสารแนบ (Attachments)"
                        haveatt = True
                    ElseIf row.err = 2 Then

                        txtErr = "ครุภัณฑ์นี้ต้องการเอกสารแนบ (Attachments)"
                        haveatt = True
                    ElseIf row.err = 3 Then
                        txtErr = "ครุภัณฑ์นี้ต้องการเอกสารแนบ (Attachments)"
                        haveatt = True
                    ElseIf row.err = 4 Then
                        txtErr = "ครุภัณฑ์นี้ยังไม่มีการกระจายรายเดือน"
                    ElseIf row.err = 5 Then
                        txtErr = "ครุภัณฑ์นี้ยังการกระจายรายเดือนไม่เรียบร้อย"

                    End If
                    Dim cmmtc As String = ""
                    If row.IsCmmt_CmmtCodeNull = True Then
                        cmmtc = ""
                    Else
                        cmmtc = row.Cmmt_CmmtCode
                    End If

                    Dim proc As String = ""
                    If row.IsProject_ProjectCodeNull = True Then
                        proc = ""
                    Else
                        proc = row.Project_ProjectCode
                    End If

                    Dim actc As String = ""
                    If row.IsActivityType_ActivityTypeCodeNull = True Then
                        actc = ""
                    Else
                        actc = row.ActivityType_ActivityTypeCode
                    End If
                    Dim NewQuantity As Integer = 0
                    If row.IsNewQuantityNull = True Then
                        NewQuantity = 0
                    Else
                        NewQuantity = row.NewQuantity
                    End If
                    Dim ReplaceQuantity As Integer = 0
                    If row.IsReplaceQuantityNull = True Then
                        ReplaceQuantity = 0
                    Else
                        ReplaceQuantity = row.ReplaceQuantity
                    End If
                    Dim Amount As Decimal = 0
                    If row.IsAmountNull = True Then
                        Amount = 0
                    Else
                        Amount = row.Amount
                    End If

                    dt.Rows.Add(row.FundCenter_FundCenterCode, cmmtc, proc, actc, NewQuantity, ReplaceQuantity, Amount, txtErr)

                Next
            End If
            ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
            Dim adap As New checkPlanDSTableAdapters.checkAmount2TableAdapter
            Dim sql = " AND (PlanYear = " & Val(PlanYearsTxt.Text) & ") and (FundCenter_FundCenterCode  = '" & rows("FundCenterCode") & "') and (FormId = 'F04')  and Version = '" & rows("Now_version") & "'"
            Dim dat As New checkPlanDS.checkAmount2DataTable

            adap.GetDataByFilter(dat, sql)

            For Each row As checkPlanDS.checkAmount2Row In dat

                dt.Rows.Add(row.FundCenterCode, row.Cmmt_CmmtCode, row.Project_ProjectCode, row.ActivityType_ActivityTypeCode, row.NewQuantity, row.ReplaceQuantity, row.SumAmount, "ยังกระจายรายเดือนไม่เรียบร้อย")

            Next
            Dim dat3 As New checkPlanDS.Budget3DataTable
            Dim adap3 As New checkPlanDSTableAdapters.Budget3TableAdapter
            Dim sql3 As String = ""
            sql3 = " where  Amount <> 0 and (BudgetDetails.PlanYear = " & Val(PlanYearsTxt.Text) & ") and (BudgetDetails.FundCenter_FundCenterCode = '" & rows("FundCenterCode") & "')and (BudgetDetails.FormId = 'F04') and budgetDetails.Id NOT IN(Select BudgetDetail_Id from Budget12)  and BudgetDetails.Version = '" & rows("Now_version") & "'"

            adap3.GetDataByFilter(dat3, sql3)
            For Each row As checkPlanDS.Budget3Row In dat3
                dt.Rows.Add(row.FundCenter_FundCenterCode, row.Cmmt_CmmtCode, row.Project_ProjectCode, row.ActivityType_ActivityTypeCode, row.NewQuantity, row.ReplaceQuantity, row.Amount, "รายการนี้ยังไม่มีการกระจายรายเดือน")

            Next

            ''''''

        Next
        ' MsgBox(totalFundCenter)
        'Exit Function
        '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''


        Return dt
    End Function


    Function checkError_No04() As DataTable
        Dim totalFundCenter As String = ""
        Dim dd As New DataTable
        dd = WebGrid1.DataSource
        If dd.Rows.Count = 0 Then
            Exit Function
        End If

        Dim dt As New DataTable
        dt.Columns.Add("FundCenterCode", GetType(String))
        'dt.Columns.Add("FundCName", GetType(String))
        dt.Columns.Add("CmmtCode", GetType(String))
        dt.Columns.Add("Project_ProjectCode", GetType(String))
        dt.Columns.Add("CmmtDetail_Id", GetType(Integer))
        dt.Columns.Add("Product_ProductCode", GetType(String))
        dt.Columns.Add("Activity_ActivityCode", GetType(String))
        dt.Columns.Add("Amount", GetType(Decimal))
        dt.Columns.Add("err", GetType(String))


        ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''



        Dim adap4 As New checkPlanDSTableAdapters.BudgetDetailsTableAdapter
        Dim check As New checkPlanDS.BudgetDetailsDataTable
        Dim text As String = "ISNULL(Amount,0) as Amount, ISNULL(NewQuantity,0) as NewQuantity, ISNULL(ReplaceQuantity,0) as ReplaceQuantity, ISNULL(ActivityType_ActivityTypeCode, ' ') AS ActivityType_ActivityTypeCode, FundCenter_FundCenterCode,   FundCenter_PlanYear, ISNULL(Project_ProjectCode, ' ') AS Project_ProjectCode, Project_PlanYear, Project_FundCenterCode, ISNULL(Cmmt_CmmtCode, ' ')    AS Cmmt_CmmtCode, Cmmt_PlanYear"
        Dim sql4 As String = ""


        For Each rows As DataRow In dd.Rows

            'sql4 += " SELECT " & text & " ,'4' as err from  BudgetDetails  "
            'sql4 += " where BudgetDetails.PlanYear = " & Val(PlanYearsTxt.Text) & " AND BudgetDetails.FormId <> 'F04' and BudgetDetails.ActivityType_ActivityTypecode IS NULL AND BudgetDetails.Id NOT IN(Select Budget12.BudgetDetail_Id from Budget12) and BudgetDetails.FundCenter_FundCenterCode  = '" & rows("FundCenterCode") & "' and BudgetDetails.Version = '" & rows("Now_version") & "'"



            'adap4.GetDataByFilter(check, sql4)



            'If check.Count > 0 Then
            '    Dim txtErr As String = ""
            '    For Each row As checkPlanDS.BudgetDetailsRow In check
            '        If row.err = 1 Then
            '            txtErr = "รายการนี้ต้องการเอกสาร"

            '        ElseIf row.err = 2 Then

            '            txtErr = "รายการนี้ต้องการเอกสาร"
            '        ElseIf row.err = 3 Then
            '            txtErr = "รายการที่ไม่มีราคามาตรฐาน ต้องการเอกสาร"
            '        ElseIf row.err = 4 Then
            '            txtErr = "รายการนี้ยังไม่มีการกระจายรายเดือน"

            '        End If
            '        Dim cmmtc As String = ""
            '        If row.IsCmmt_CmmtCodeNull = True Then
            '            cmmtc = ""
            '        Else
            '            cmmtc = row.Cmmt_CmmtCode
            '        End If

            '        Dim proc As String = ""
            '        If row.IsProject_ProjectCodeNull = True Then
            '            proc = ""
            '        Else
            '            proc = row.Project_ProjectCode
            '        End If

            '        Dim actc As String = ""
            '        If row.IsActivityType_ActivityTypeCodeNull = True Then
            '            actc = ""
            '        Else
            '            actc = row.ActivityType_ActivityTypeCode
            '        End If
            '        Dim NewQuantity As Integer = 0
            '        If row.IsNewQuantityNull = True Then
            '            NewQuantity = 0
            '        Else
            '            NewQuantity = row.NewQuantity
            '        End If
            '        Dim ReplaceQuantity As Integer = 0
            '        If row.IsReplaceQuantityNull = True Then
            '            ReplaceQuantity = 0
            '        Else
            '            ReplaceQuantity = row.ReplaceQuantity
            '        End If
            '        Dim Amount As Integer = 0
            '        If row.IsAmountNull = True Then
            '            Amount = 0
            '        Else
            '            Amount = row.Amount
            '        End If

            '        dt.Rows.Add(row.FundCenter_FundCenterCode, cmmtc, proc, Amount, txtErr)
            '    Next
            ' End If




            ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
            Dim adap As New checkPlanDSTableAdapters.checkAmount2TableAdapter
            Dim sql As String = ""
            sql += " SELECT        ISNULL(BudgetDetails.FundCenter_FundCenterCode, '') AS FundCenterCode, ISNULL(BudgetDetails.Cmmt_CmmtCode, '') AS Cmmt_CmmtCode "
            sql += " , ISNULL(BudgetDetails.Project_ProjectCode, '') AS Project_ProjectCode, ISNULL(BudgetDetails.ActivityType_ActivityTypeCode, '') AS ActivityType_ActivityTypeCode "
            sql += " , ISNULL(BudgetDetails.NewQuantity, 0) AS NewQuantity, ISNULL(BudgetDetails.ReplaceQuantity, 0) AS ReplaceQuantity, ISNULL(BudgetDetails.Amount, 0) AS SumAmount, BudgetDetails.Id"
            sql += " , BudgetDetails.CmmtDetail_Id, ISNULL(BudgetDetails.Product_ProductCode,'') AS Product_ProductCode, ISNULL(BudgetDetails.Activity_ActivityCode,'') AS Activity_ActivityCode "
            sql += " , BudgetDetails.Id"
            sql += " FROM BudgetDetails INNER JOIN Budget12 ON BudgetDetails.Id = Budget12.BudgetDetail_Id "
            sql += " WHERE      (BudgetDetails.Amount > 0) and  (BudgetDetails.Amount <> (Amount1 + Amount2 + Amount3 + Amount4 + Amount5 + Amount6 + Amount7 + Amount8 + Amount9 + Amount10 + Amount11 + Amount12)) "
            sql += " AND (BudgetDetails.PlanYear = " & Val(PlanYearsTxt.Text) & ") and (BudgetDetails.FundCenter_FundCenterCode = '" & rows("FundCenterCode") & "') and (BudgetDetails.FormId <> 'F04') and BudgetDetails.Version = '" & rows("Now_version") & "'"
            sql += " AND (Amount1 + Amount2 + Amount3 + Amount4 + Amount5 + Amount6 + Amount7 + Amount8 + Amount9 + Amount10 + Amount11 + Amount12) <> 0 "
            Dim dat As New checkPlanDS.checkAmount2DataTable

            adap.GetDataByFilter(dat, sql)


            For Each row As checkPlanDS.checkAmount2Row In dat

                dt.Rows.Add(row.FundCenterCode, row.Cmmt_CmmtCode, row.Project_ProjectCode, If(row.IsCmmtDetail_IdNull, Nothing, row.CmmtDetail_Id), row.Product_ProductCode, row.Activity_ActivityCode, row.SumAmount, "ยังกระจายรายเดือนไม่เรียบร้อย")

            Next
            Dim dat3 As New checkPlanDS.Budget3DataTable
            Dim adap3 As New checkPlanDSTableAdapters.Budget3TableAdapter
            Dim sql3 As String = ""
            sql3 += " WHERE Amount <> 0 and (BudgetDetails.PlanYear = " & Val(PlanYearsTxt.Text) & ") and (BudgetDetails.FundCenter_FundCenterCode  = '" & rows("FundCenterCode") & "') and (BudgetDetails.FormId <> 'F04') and budgetDetails.Id NOT IN(Select BudgetDetail_Id from Budget12) and BudgetDetails.Version = '" & rows("Now_version") & "'"
            sql3 += " UNION "
            sql3 += " SELECT        ISNULL(BudgetDetails.Amount, 0) AS Amount, ISNULL(BudgetDetails.FundCenter_FundCenterCode, '') AS FundCenter_FundCenterCode"
            sql3 += " , ISNULL(BudgetDetails.Project_ProjectCode, '') AS Project_ProjectCode "
            sql3 += " , ISNULL(BudgetDetails.Cmmt_CmmtCode, '') AS Cmmt_CmmtCode, ISNULL(BudgetDetails.NewQuantity, 0) AS NewQuantity "
            sql3 += " , ISNULL(BudgetDetails.ReplaceQuantity, 0) AS ReplaceQuantity "
            sql3 += " , ISNULL(BudgetDetails.ActivityType_ActivityTypeCode, '') AS ActivityType_ActivityTypeCode "
            sql3 += " , BudgetDetails.CmmtDetail_Id, ISNULL(BudgetDetails.Product_ProductCode,'') AS Product_ProductCode, ISNULL(BudgetDetails.Activity_ActivityCode,'') AS Activity_ActivityCode "
            sql3 += " , BudgetDetails.Id"
            sql3 += " FROM BudgetDetails INNER JOIN Budget12 ON BudgetDetails.Id = Budget12.BudgetDetail_Id "
            sql3 += " WHERE Amount <> 0 and (BudgetDetails.PlanYear = " & Val(PlanYearsTxt.Text) & ")  and (BudgetDetails.FundCenter_FundCenterCode  = '" & rows("FundCenterCode") & "') and (BudgetDetails.FormId <> 'F04')  and (Amount1 + Amount2 + Amount3 + Amount4 + Amount5 + Amount6 + Amount7 + Amount8 + Amount9 + Amount10 + Amount11 + Amount12) = 0  and BudgetDetails.Version = '" & rows("Now_version") & "'"


            adap3.GetDataByFilter(dat3, sql3)
            For Each row As checkPlanDS.Budget3Row In dat3
                dt.Rows.Add(row.FundCenter_FundCenterCode, row.Cmmt_CmmtCode, row.Project_ProjectCode, If(row.IsCmmtDetail_IdNull, Nothing, row.CmmtDetail_Id), row.Product_ProductCode, row.Activity_ActivityCode, row.Amount, "รายการนี้ยังไม่มีการกระจายรายเดือน")
            Next





        Next


        Return dt
    End Function


    Protected Sub SendBtn_Click(sender As Object, e As ImageClickEventArgs) Handles SendBtn.Click
        Session.LCID = 2057
        Dim i As Integer = 0
        i = WebGrid2.RootTable.Rows.Count
        i = i + WebGrid3.RootTable.Rows.Count
        ' MsgBox(HdMyVersion.Value)
        If i > 0 Then
            Alert("กรุณาแก้ไขข้อผิดพลาดของรายการงบประมาณก่อนส่งแผน")
            '  WebGrid1.ClientAction.Alert("กรุณาแก้ไขข้อผิดพลาดของรายการงบประมาณก่อนส่งแผน")
            Exit Sub
        Else
            Dim exist As Integer
            Dim dd As New DataTable
            dd = WebGrid1.DataSource
            Dim adap As New checkPlanDSTableAdapters.FundCenterReleasesTableAdapter
            Try
                If Val(dd.Rows.Count) = 0 Then
                    Alert("ไม่มีแผนที่สามารถส่งได้")
                    Exit Sub
                End If
            Catch ex As Exception
                Alert("ไม่มีแผนที่สามารถส่งได้")
                Exit Sub
            End Try
            'check ถ้ายังไม่ได้สร้างแผน ส่งแผนไม่ได้
            'Dim adapter As New FundCenter2TableAdapters.BudgetDetailsTableAdapter
            'Dim dataCheck As FundCenter2.BudgetDetailsDataTable
            'Dim countPln As Integer = 0
            'For Each chrow As DataRow In dd.Rows
            '    dataCheck = Adapter.CheckBudget(chrow.Item("FundCenterCode"), chrow.Item("Now_version"), Val(PlanYearsTxt.Text))
            '    If dataCheck.Count = 0 Then
            '        countPln = countPln + 1
            '    End If
            'Next
            'If countPln > 0 Then
            '    Alert("มี " & countPln & " หน่วยงาน ที่ยังไม่ได้สร้างแผน")
            '    Exit Sub
            'End If

            If dd.Rows.Count > 0 Then
                Dim adap2 As New FundCenter2TableAdapters.FundCenterReleasesTableAdapter
                Dim precheck As String
                precheck = adap2.GetReleaseFlag(dd.Rows(0).Item("FundCenterCode"), dd.Rows(0).Item("Now_version"), Val(PlanYearsTxt.Text))

                If precheck = "Y" Then
                    Alert("มีการดำเนินการส่งแผนไปแล้ว ไม่สามารถส่งแผนซ้ำได้")
                    GetData()
                    Exit Sub
                End If
            End If
            For Each row As DataRow In dd.Rows
                exist = adap.checkExist(row.Item("FundCenterCode"), Val(PlanYearsTxt.Text), row.Item("Now_version"))
                If exist = 0 Then
                    adap.InsertQuery(Val(PlanYearsTxt.Text), "Y", "Y", Date.Now, Nothing, Session("users"), Nothing, row.Item("FundCenterCode"), Val(PlanYearsTxt.Text), row.Item("Now_version"), "N", "", 0)
                Else

                    Dim adap2 As New checkPlanDSTableAdapters.FundCenterReleasesTableAdapter
                    Dim maxvers As String = adap.GetMaxVersion(row.Item("FundCenterCode"), Val(PlanYearsTxt.Text))
                    If Val(row.Item("Now_version")) >= Val(maxvers) Then
                        adap.UpdateSendPlan("Y", Date.Now, Session("users"), "Y", row.Item("Now_version"), row.Item("FundCenterCode"), Val(PlanYearsTxt.Text))
                    End If
                End If
            Next

            logger.Info("User " & Session("users") & " submit budget plan ")

            'SendBtn.Enabled = False
            GetData()
            Alert("ดำเนินการส่งแผน เรียบร้อยแล้ว")
        End If


    End Sub
    Sub Alert(ByVal message As String)
        AlertText = "<script> alert('" & message & "');</script>"
    End Sub


    Protected Sub WebGrid3_InitializeRow(sender As Object, e As RowEventArgs) Handles WebGrid3.InitializeRow
        If Val(e.Row.Cells(1).Value) = 0 Then
            e.Row.Cells(1).Value = ""
            e.Row.Cells(1).Text = ""
        End If
    End Sub
End Class